package com.jungle.client;

import com.google.gson.reflect.TypeToken;
import com.jungle.bfi.domain.vo.Option;
import com.jungle.bfi.domain.vo.VoucherEntryTemplateVo;
import com.jungle.bfi.domain.vo.VoucherTypeVo;
import com.jungle.client.channel.HttpClient;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Consumer;

@Slf4j
public class VoucherTemplateController implements Initializable {
    @FXML
    private VBox vBox;
    @FXML
    private ComboBox<Option> characterComboBox;
    @FXML
    private Button editButton;
    @FXML
    private Button deleteButton;
    @FXML
    private TableView<VoucherEntryTemplateVo> tableView;

    private final ObservableList<Option> voucherTypeOptions = FXCollections.observableArrayList();
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        log.info("init VoucherTemplateController, url:{}", url);
        initVoucherCharacter();
        //vBox.getChildren().add(0, createLegendItem("借方", Color.RED));
    }
    private HBox createLegendItem(String text, Color color) {
        HBox hbox = new HBox(5); // 水平布局，间距为5

        // 创建一个矩形作为颜色标识
        Rectangle colorRect = new Rectangle(15, 15);
        colorRect.setFill(color);

        // 创建一个标签作为文本
        Label label = new Label(text);

        // 将矩形和标签添加到HBox中
        hbox.getChildren().addAll(colorRect, label);

        return hbox;
    }
    private void initVoucherCharacter() {
        log.info("init voucherCharacterHBox");
        HttpClient.getInstance().post("/voucherType/list", "{}").callback(new TypeToken<List<VoucherTypeVo>>() {
        }, list -> {
            if (list != null && !list.isEmpty()) {
                for (VoucherTypeVo voucherTypeVo : list) {
                    voucherTypeOptions.add(new Option(voucherTypeVo.getName(), voucherTypeVo.getValue()));
                }
            }
        });

        characterComboBox.setItems(voucherTypeOptions);
    }
    @FXML
    private void doAdd(ActionEvent actionEvent) {
        log.info("doAdd:{}", actionEvent);
        try {
            EntryTemplateEditController.showAddDialog(new VoucherEntryTemplateVo(), data -> {
                log.info("addDialog data:{}", data);
                if (data != null) {
                    HttpClient.getInstance().post("/dataCategory/store", data).callback(VoucherEntryTemplateVo.class, resp -> {
                        if (resp != null) {
                            tableView.getItems().add(resp);
                        }
                    });
                }
            });
        } catch (IOException e) {
            log.error("showAddDialog error", e);
        }
    }

    @FXML
    private void doEdit(ActionEvent actionEvent) {
        log.info("doEdit:{}", actionEvent);
        int index = tableView.getSelectionModel().getSelectedIndex();

        try {
            VoucherEntryTemplateVo entryTemplateVo = tableView.getItems().get(index);
            EntryTemplateEditController.showEditDialog(entryTemplateVo, data -> {
                log.info("editDialog data:{}", data);
                if (data != null) {
                    HttpClient.getInstance().post("/dataCategory/store", data).callback(VoucherEntryTemplateVo.class, resp -> {
                        if (resp != null) {
                            tableView.getItems().set(index, resp);
                        }
                    });
                }
            });
        } catch (IOException e) {
            log.error("showEditDialog error", e);
        }
    }

    @FXML
    private void doDelete(ActionEvent actionEvent) {
        log.info("doDelete:{}", actionEvent);
        VoucherEntryTemplateVo selectedItem = tableView.getSelectionModel().getSelectedItem();
        doDelete(selectedItem);
    }

    private void doDelete(VoucherEntryTemplateVo selectedItem) {
        if (selectedItem == null) {
            return;
        }
        new Alert(Alert.AlertType.WARNING, "确定删除吗？")
                .showAndWait().ifPresent(doOk(()->{
                        log.info("删除选中的行");
                        String itemId = selectedItem.getId();
                        if (itemId == null) {
                            tableView.getItems().remove(selectedItem);
                        } else {
                            HttpClient.getInstance().post("/dataCategory/delete", itemId).callback(Void.class,
                                    resp -> {
                                        log.info("resp:{}", resp);
                                        tableView.getItems().remove(selectedItem);
                                    }
                            );
                        }

                }));
    }

    private static Consumer<ButtonType> doOk(Runnable runnable) {
        return result -> {
            if (result == ButtonType.OK) {
                log.info("doOk");
                runnable.run();
            }
        };
    }
}
